package org.example.springcloudgateway.filter;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.JwtUtil.JwtUtils;
import org.example.Response.ApiResponse;
import org.example.dao.entity.User;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

public class JwtAuthenticationFilter  implements GatewayFilter {

    private JwtUtils jwtUtils;
    private final ObjectMapper objectMapper = new ObjectMapper();

    public JwtAuthenticationFilter(String secretKey) {
        this.jwtUtils = new JwtUtils(secretKey);
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getURI().getPath();
        try {
        // 判断路径后缀是否是 .action
        if (path.endsWith(".action")) {
            String token = exchange.getRequest().getHeaders().getFirst("Authorization");

            if (token == null || !token.startsWith("Bearer ")) {
                return unauthorizedResponse(exchange,"token invalid or Bearer token");
            }

            token = token.substring(7); // 去掉 "Bearer " 前缀

          try{
              User user = jwtUtils.getUserInfo(token);


              if (user == null) {
                  return unauthorizedResponse(exchange,"token invalid UserInfo");
              }

              return chain.filter(exchange); // Token 有效，继续请求

          } catch (JWTVerificationException e) {
              if (e instanceof SignatureVerificationException) {
                  return unauthorizedResponse(exchange,"Invalid signature: " + e.getMessage());
              } else if (e instanceof TokenExpiredException) {
                  return unauthorizedResponse(exchange,"Token has expired: " + e.getMessage());
              } else if (e instanceof AlgorithmMismatchException) {
                  return unauthorizedResponse(exchange,"Algorithm mismatch: " + e.getMessage());
              }else  {
                  return unauthorizedResponse(exchange,"Token verification failed: " + e.getMessage());
              }
          }

        }
        } catch (Exception e) {
            try {
                return unauthorizedResponse(exchange,"Unauthorized"); // Token 无效，返回 401
            } catch (JsonProcessingException ex) {
                throw new RuntimeException(ex);
            }
        }
        // 对于以 .do 结尾的请求，跳过 JWT 认证，直接放行
        return chain.filter(exchange);
    }

    private Mono<Void> unauthorizedResponse(ServerWebExchange exchange,String str) throws JsonProcessingException {
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        ApiResponse resp = new ApiResponse(HttpStatus.UNAUTHORIZED.value(),null, str);
        byte[] responseBytes = objectMapper.writeValueAsBytes(resp);
        return exchange.getResponse().writeWith(Mono.just(exchange.getResponse().bufferFactory().wrap(responseBytes)));
    }
}
